package edu.cuny.baruch.cis9590.library.database;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public abstract class LibraryDAO<T> {
    
    @SuppressWarnings("deprecation")
    private static final SessionFactory SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
    
    public final List<T> getAll() {
        return query("from " + getEntityClass().getSimpleName());
    }
    
    public T getById(int id) {
        Session session = SESSION_FACTORY.openSession();
        T entity = (T) session.byId(getEntityClass()).load(Integer.valueOf(id));
        session.close();
        return entity;
    }
    
    protected abstract Class<T> getEntityClass();
    
    public void delete(T entity) {
        Session session = SESSION_FACTORY.openSession();
        session.beginTransaction();
        session.delete(entity);
        session.getTransaction().commit();
        session.close();
    }
    
    public void insert(T entity) {
        Session session = SESSION_FACTORY.openSession();
        session.beginTransaction();
        session.save(entity);
        session.getTransaction().commit();
        session.close();
    }
    
    protected final List query(String query) {
        Session session = SESSION_FACTORY.openSession();
        List list = session.createQuery(query).list();
        session.close();
        return list;
    }
    
    public void update(T entity) {
        Session session = SESSION_FACTORY.openSession();
        session.beginTransaction();
        session.update(entity);
        session.getTransaction().commit();
        session.close();
    }
}
